package com.amber.proyecto.envia.imagenes.sw.camara;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.amber.proyecto.envia.imagenes.sw.EnviaImagenSW;
import com.amber.proyecto.envia.imagenes.sw.Principal;
import com.amber.proyecto.envia.imagenes.sw.R;
import com.amber.proyecto.envia.imagenes.sw.utils.Variables;



public class ObtieneImgCam extends Activity implements SurfaceHolder.Callback {
	private LayoutInflater mInflater = null;
	private Camera mCamera;
	private boolean mPreviewRunning = false;
	private SurfaceHolder mSurfaceHolder;
	private SurfaceView mSurfaceView;
	private Bundle bundle;
	private String ruta = Variables.ruta;
	private File archivo;
	private FileOutputStream archivoAlmacenado;
	private String nombreImagen = "FT"+System.currentTimeMillis();
	private LocationManager milocManager;
	private Location coordenadas;
	private ImageView ivAtras;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.obtieneimgcam);
		
	    bundle = getIntent().getExtras();

	    File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString());
	    if(!folder.exists()){
	      folder.mkdirs();
	    }
		
	    activaGPS();
	    

		
		archivo = new File(ruta,nombreImagen+Variables.tipoArchivo);
		
		
		mSurfaceView = (SurfaceView)findViewById(R.id.surfaceCam);
		mSurfaceView.setOnClickListener(mSurfPres);
		/*
	    ivAtras = (ImageView)findViewById(R.id.ivAtrasFotoCO);
	    ivAtras.setOnClickListener(ivAtrasPres);
		*/
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		mInflater = LayoutInflater.from(this);
		View overView = mInflater.inflate(R.layout.cameraoverlay, null);
		this.addContentView(overView,new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		milocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, milocListener);
		
		
	}
	
	private OnClickListener ivAtrasPres = new OnClickListener() {

		public void onClick(View v) {
			Intent intent = new Intent();
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.setClass(ObtieneImgCam.this, Principal.class);
			startActivity(intent);
		}
	};
	
	private OnClickListener mSurfPres = new OnClickListener() {

		public void onClick(View v) {
			milocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, milocListener);
			if (coordenadas != null){
				mCamera.takePicture(mShutterCallback,mPictureCallback, mjpeg);
				Toast.makeText(ObtieneImgCam.this, "Guardando imagen...", Toast.LENGTH_LONG).show();
				try {
			    	Thread.sleep (2000);
			    	} catch (Exception e) {
			    	// Mensaje en caso de que falle
			    	}
			    finally{
			    	
					  //abrimos la actividad que envía la imagen
					  Intent intent = new Intent();
					  intent.setClass(ObtieneImgCam.this, EnviaImagenSW.class);
					  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					  intent.putExtra("ruta", ruta);
					  intent.putExtra("nombreImagen", nombreImagen+Variables.tipoArchivo);
					  intent.putExtra("latitud", coordenadas.getLatitude());
					  intent.putExtra("longitud", coordenadas.getLongitude());
					  intent.putExtra("correoUsuario", bundle.getString("correoUsuario"));
					  
					  if (getIntent().hasExtra("inicioSesion")){
						  intent.putExtra("inicioSesion", true);
					  }
					  
					  startActivity(intent);
					  finish();
			    }
			}else{
				Toast.makeText(ObtieneImgCam.this, "Obteniendo ubicación GPS, intente nuevamente...",Toast.LENGTH_LONG).show();
			}		
		}
	};
	
	
	  private LocationListener milocListener = new LocationListener() {

			public void onStatusChanged(String provider, int status, Bundle extras) {

				
			}

			public void onProviderEnabled(String provider) {

				
			}

			public void onProviderDisabled(String provider) {

				
			}

			public void onLocationChanged(Location location) {
				  //String coordenadas = "Mis coordenadas son: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude();
				  coordenadas = location;
				  if (coordenadas == null){
					  //latitud = bundle.getDouble("latitud");
					  //longitud = bundle.getDouble("longitud");
				  }
				
			}
		};
	
	private void activaGPS(){
		milocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
	    milocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, milocListener);
	}
	
	ShutterCallback mShutterCallback = new ShutterCallback(){
	
	public void onShutter() {}
	};
	
	PictureCallback mPictureCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera c) {}
	};
	
	PictureCallback mjpeg = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera c) {
			if(data !=null) {
			      File outStream = null;
			      try {
				        // Write to SD Card
			    	  boolean mExternalStorageAvailable = false;
			    	  boolean mExternalStorageWriteable = false;
			    	  String state = Environment.getExternalStorageState();

			    	  if (Environment.MEDIA_MOUNTED.equals(state)) {
			    	      // We can read and write the media
			    		
			    	      mExternalStorageAvailable = mExternalStorageWriteable = true;
				    	  
					      archivoAlmacenado = new FileOutputStream(archivo);
					      archivoAlmacenado.write(data);
					      archivoAlmacenado.close();
			    	  }

			      } catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}			
			}
			
		}
	};
		
	
		public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
			try {
				if (mPreviewRunning) {
					mCamera.stopPreview();
					mPreviewRunning = false;
				}
				/*Camera.Parameters p = mCamera.getParameters();
				p.setPreviewSize(w, h);
				mCamera.setParameters(p);*/
				mCamera.setPreviewDisplay(holder);
				mCamera.startPreview();
			
				mPreviewRunning = true;
			} catch(Exception e) {

			}
		}
	
		public void surfaceCreated(SurfaceHolder holder) {
			milocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, milocListener);
			mCamera = Camera.open();
			if (Variables.tamResolucion != null){
				Camera.Parameters params = mCamera.getParameters();
				params.setPictureSize(Variables.tamResolucion.width, Variables.tamResolucion.height);
				mCamera.setParameters(params);
			}
		}
	
		public void surfaceDestroyed(SurfaceHolder holder) {
			mCamera.stopPreview();
			mPreviewRunning = false;
			mCamera.release();
			mCamera=null;
		}
}
